package com.read.controller;

import com.read.common.annotation.UserLoginToken;
import com.read.service.MailService;
import com.read.util.RedisUtil;
import com.read.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sh-sunb6
 * @description 邮箱 Controller
 * @date 2019-02-22 14:19
 */
@Api(tags = "邮箱服务相关 Controller")
@RestController
@RequestMapping("mail")
public class MailController {

    private static final Logger logger = LoggerFactory.getLogger(MailController.class);

    @Autowired
    private MailService mailService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @ApiOperation(value = "发送邮件", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "系统token", required = true, paramType = "header"),
            @ApiImplicitParam(name="email", value="邮箱", required=true, paramType="query", dataType = "String", defaultValue = "")
    })
    @UserLoginToken
    @GetMapping("/send")
    public void sendEmail(String email) {

        if (StringUtil.isNotEmpty(email)) {
            String emailCode = StringUtil.randomCode();

            logger.info("接收者邮箱：{}, 邮箱验证码：{}", email, emailCode);

            //保存redis,10分钟有效
            redisUtil.set("emailCode_" + email, emailCode, 600);

            mailService.sendMail(fromEmail, email, emailCode);
        }
    }

}
